package top.glkj.hms.entity;

import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import top.glkj.hms.utils.Status;

import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 用户权限表
 *
 * @author : xgl
 * @version : 0.0.1
 * @date :2020/11/1 0:35
 */
@Entity
@Table(name = "hms_permission")
@Getter
@Setter
public class Permission extends BaseEntity {
    /**
     * 权限名称
     */
    @Column(name = "permission_name", nullable = false)
    private String permissionName;
    /**
     * 权限简码
     */
    @Column(name = "permission_code", nullable = false, unique = true)
    private String permissionCode;
    /**
     * 权限资源
     */
    @Fetch(FetchMode.SUBSELECT)
    @ManyToMany(targetEntity = Resource.class, cascade = CascadeType.ALL)
    @JoinTable(name = "hms_permissions_resources",
            //当前对象在中间表中的外键
            joinColumns = {@JoinColumn(name = "permission_id", referencedColumnName = "id")},
            //对方对象在中间表中的外键
            inverseJoinColumns = {@JoinColumn(name = "resource_id", referencedColumnName = "id")}
    )
    private Set<Resource> resources= new HashSet<>();
    /**
     * 父级权限
     */
    @OneToOne
    @JoinColumn(name = "permission_parent_id", referencedColumnName = "id")
    private Permission parent;
    /**
     * 权限描述
     */
    private String description;
    @Transient
    private List<Permission> children;
    /**
     * 状态码
     */
    private Status status;

    //@ManyToMany(mappedBy = "permissions", fetch = FetchType.EAGER)
    //private Set<Role> roles;


    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof Permission)) {
            return false;
        }
        Permission that = (Permission) o;
        return Objects.equals(getPermissionName(), that.getPermissionName())
                && Objects.equals(getPermissionCode(), that.getPermissionCode())
                && Objects.equals(getCreateUserId(), that.getCreateUserId())
                && Objects.equals(getParent(), that.getParent())
                && Objects.equals(getDescription(), that.getDescription())
                && getStatus() == that.getStatus();
    }

    @Override
    public int hashCode() {
        return Objects.hash(getPermissionName(),
                getPermissionCode(),
                getCreateUserId(),
                getParent(),
                getDescription(),
                getStatus());
    }
}
